<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Reward;
use Illuminate\Support\Facades\Cache;
use Carbon\Carbon;
use Brick\Math\RoundingMode;
use Illuminate\Database\Eloquent\Builder;

class RewardsController extends Controller
{
	public function records()
	{
		$user = request()->user();
		$condition = request('condition');

		if(!$condition){
			$query = Reward::query();
		}else{

			$query = Reward::query()->where('remark',$condition);
		}
		

		$query = $query->where('user_id', $user->id);
		$query = !empty(request('start_time')) ? $query->where('created_at', '>', request('start_time')) : $query;
		$query = !empty(request('end_time')) ? $query->where('created_at', '<', request('end_time')) : $query;
	
		$total = $query->sum('money');
		$cards = $query->orderByDesc('id')->paginate();

		
		return ['total' => $total, 'data' => $cards];
	}

	public function oneDayRecords()
	{
		$user = request()->user();
		$time  = request('time') ?? Carbon::today();
		
		$ownRewards = $user->rewards()->whereDate("created_at",$time)->where(function (Builder $query) {
 						 $query->where('remark','own_order')->orWhere('remark', 'rewards_refund');
				})->sum('money');
		$parentRewards = $user->rewards()->whereDate("created_at",$time)->where(function (Builder $query) {
 						 $query->where('remark','first_level')->orWhere('remark', 'rewards_refund_first');
				})->sum('money');
		$teamRewards = $user->rewards()->whereDate("created_at",$time)->where(function (Builder $query) {
 						 $query->where('remark','second_level')->orWhere('remark', 'rewards_refund_second');
				})->sum('money');


		$data = [
			'own_rewards' => $ownRewards ? $ownRewards : '0.00' ,
			'parents_rewards' => $parentRewards ? $parentRewards : '0.00' ,
			'team_rewards' => $teamRewards ? $teamRewards : '0.00' ,

		];
		
		return ['data' => $data];
	}
}
